var mqtt = require('../../utils/mqtt.min.js')
const crypto = require('../../utils/hex_hmac_sha1.js');
var mes = 'hellworld';
Page({
  data: {
    test:[
      "a",
      "b",
      "c"
    ],
    mesitem:''
  },
  onLoad: function () {
    this.doConnect()
  },
  doConnect() {
    const deviceConfig = {
      productKey: "a13eB4d2gqJ",
      deviceName: "sHU6aelT8VqNf7387lde",
      deviceSecret: "rWKEYDt69jnfb5lVwZda1g1jCg7GpDT0",
      regionId: "cn-shanghai"
    };
    const options = this.initMqttOptions(deviceConfig);
    console.log(options)
    //替换productKey为你自己的产品的
    const client = mqtt.connect('wxs://productKey.iot-as-mqtt.cn-shanghai.aliyuncs.com', options)
    client.on('connect', function () {
      console.log('连接服务器成功')
      //订阅主题，替换productKey和deviceName(这里的主题可能会不一样，具体请查看后台设备Topic列表或使用自定义主题)
      client.subscribe('/productKey/deviceName/user/get', function (err) {
        if (!err) {
          console.log('订阅成功！');
        }
      })
    })
    //接收消息监听
    client.on('message', function (topic, message) {
      // message is Buffer
      console.log('收到消息：' + message.toString())
      mes = message.toString()
      console.log(mes);
      // that.setData({
      //   mesitem: mes
      // })
      //关闭连接 client.end()
    })
  },
  _testTap:function(ev) {
    console.log("1111");
    // this.data.test.push(message);
    // console.log(this.data.test)
    console.log(mes,ev);
    this.setData({
      mesitem:mes
    })
  },
  //IoT平台mqtt连接参数初始化
  initMqttOptions(deviceConfig) {

    const params = {
      productKey: deviceConfig.productKey,
      deviceName: deviceConfig.deviceName,
      timestamp: Date.now(),
      clientId: Math.random().toString(36).substr(2),
    }
    //CONNECT参数
    const options = {
      keepalive: 60, //60s
      clean: true, //cleanSession不保持持久会话
      protocolVersion: 4 //MQTT v3.1.1
    }
    //1.生成clientId，username，password
    options.password = this.signHmacSha1(params, deviceConfig.deviceSecret);
    options.clientId = `${params.clientId}|securemode=2,signmethod=hmacsha1,timestamp=${params.timestamp}|`;
    options.username = `${params.deviceName}&${params.productKey}`;

    return options;
  },

  /*
    生成基于HmacSha1的password
    参考文档：https://help.aliyun.com/document_detail/73742.html?#h2-url-1
  */
  signHmacSha1(params, deviceSecret) {

    let keys = Object.keys(params).sort();
    // 按字典序排序
    keys = keys.sort();
    const list = [];
    keys.map((key) => {
      list.push(`${key}${params[key]}`);
    });
    const contentStr = list.join('');
    return crypto.hex_hmac_sha1(deviceSecret, contentStr);
  }
})
